<template>
  <div class="admin-management">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="管理员用户名">
          <el-input v-model="searchForm.username" placeholder="请输入管理员用户名" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="success" @click="handleAddAdmin">新增管理员</el-button>
    </div>

    <!-- 管理员表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="adminId" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="typeText" label="类型">
        <template #default="scope">
          {{ scope.row.type === 0 ? '普通管理员' : '超级管理员' }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column prop="updateTime" label="更新时间" width="160" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditAdmin(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteAdmin(scope.row.adminId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40%">
      <el-form :model="currentAdmin" :rules="rules" ref="adminFormRef">
        <el-form-item label="用户名" prop="username" label-width="80px">
          <el-input v-model="currentAdmin.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" label-width="80px">
          <el-input v-model="currentAdmin.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" label-width="80px">
          <el-input v-model="currentAdmin.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone" label-width="80px">
          <el-input v-model="currentAdmin.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="类型" prop="type" label-width="80px">
          <el-select v-model="currentAdmin.type" placeholder="请选择类型">
            <el-option :value="0" label="普通管理员" />
            <el-option :value="1" label="超级管理员" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {adminDeleteOne, adminInsertOne, adminSelectPage, adminUpdateOne} from "@/api/admin.js";

const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

const searchForm = reactive({
  username: ''
})

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' | 'edit'
const currentAdmin = reactive({
  adminId: 0,
  username: '',
  password: '',
  email: '',
  phone: '',
  type: 0
})
const adminFormRef = ref(null)

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }]
}

const dialogTitle = ref('')
const handleAddAdmin = () => {
  dialogType.value = 'add'
  dialogTitle.value = '新增管理员'
  dialogVisible.value = true
  resetForm()
}

const handleEditAdmin = (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑管理员'
  dialogVisible.value = true
  Object.assign(currentAdmin, row)
}

const handleDeleteAdmin = (adminId) => {
  ElMessageBox.confirm('确定要删除该管理员吗？', '警告', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    try {
      await adminDeleteOne(adminId)
      ElMessage.success('删除成功')
      await fetchAdminList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSubmit = () => {
  adminFormRef.value.validate(async valid => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await adminInsertOne(currentAdmin)
        } else {
          await adminUpdateOne(currentAdmin)
        }
        ElMessage.success('保存成功')
        dialogVisible.value = false
        await fetchAdminList()
        resetForm()
      } catch (error) {
        ElMessage.error('保存失败')
      }
    }
  })
}

const resetForm = () => {
  Object.assign(currentAdmin, {
    adminId: 0,
    username: '',
    password: '',
    email: '',
    phone: '',
    type: 0
  })
  adminFormRef.value?.clearValidate()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchAdminList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchAdminList()
}

// 搜索相关
const handleSearch = () => {
  currentPage.value = 1
  fetchAdminList()
}

const resetSearch = () => {
  currentPage.value = 1
  searchForm.username = ''
  fetchAdminList()
}

// 数据获取
const fetchAdminList = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      userName: searchForm.username
    }
    if (searchForm.username === '') {
      delete params.userName
    }
    const res = await adminSelectPage(params)
    tableData.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    ElMessage.error('获取管理员列表失败')
  }
}

onMounted(() => {
  fetchAdminList()
})
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.action-bar {
  margin: 15px 0;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-dialog__body) {
  padding: 20px 40px;
}
</style>
